import React, { Component } from 'react'
import request from '../utils/request'

export default class TodoHeader extends Component {
  // #1 收集数据
  state = {
    content: '',
  }
  handleKeyUp = async (e) => {
    if (e.key === 'Enter') {
      if (this.state.content.trim() === '') return alert('不能为空')
      // #2 添加到后端
      await request.post('/', { name: this.state.content })
      this.setState({ content: '' })
      // #3 前端重新获取并渲染数据
      this.props.getList()
    }
  }
  render() {
    return (
      <header className='header'>
        <h1>todos</h1>
        <input
          className='new-todo'
          placeholder='What needs to be done?'
          autoFocus
          value={this.state.content}
          onChange={(e) => this.setState({ content: e.target.value })}
          onKeyUp={this.handleKeyUp}
        />
      </header>
    )
  }
}
